package com.management.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.management.commons.OSSProperties;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.InputStream;

@Component
public class OSSTemplate {

    @Resource
    private OSSProperties ossProperties;

    private OSSClientBuilder ossBuilder=new OSSClientBuilder();

    public String uploadFile(String bucketName, String name, InputStream file){
        OSS oss=null;
        try {
             oss= ossBuilder.build(ossProperties.getEndpoint(), ossProperties.getAccessId(), ossProperties.getAccessKey());
             oss.putObject(bucketName,name,file);
            return "http://"+bucketName+"."+ossProperties.getEndpoint()+"/"+name;
        } finally {
            if (oss!=null) oss.shutdown();
        }
    }

    public String uploadFile(String name, InputStream file){
        return uploadFile(ossProperties.getBucketName(),name,file);
    }

    public void removeFile(String bucketName, String name){
        OSS oss=null;
        try {
            oss= ossBuilder.build(ossProperties.getEndpoint(), ossProperties.getAccessId(), ossProperties.getAccessKey());
            oss.deleteObject(bucketName,name );
        } finally {
            if (oss!=null) oss.shutdown();
        }
    }

    public void downloadFile(String name){
        OSS oss=null;
        try {
            oss= ossBuilder.build(ossProperties.getEndpoint(), ossProperties.getAccessId(), ossProperties.getAccessKey());
            oss.getObject(ossProperties.getBucketName(),name);
//            oss.getObject(new GetObjectRequest(ossProperties.getBucketName(),name),new File("F:\\"+name));
        } finally {
            if (oss!=null) oss.shutdown();
        }
    }
}
